/* auxlib.c */

#include "auxlib.h"

#define isdigit(c)	(c >= '0' && c <= '9')
#define isspace(c)	(c == ' ' || c == '\t' || c == '\n')

int
isSpace(char c)
{
	return (c == ' ' || c == '\t');
}


/* itoa: convert n to characters in s */

void 
itoa(int n, char * s)
{
	int i, sign;

	if ((sign = n) < 0) 	/* record sign */
		n = -n; 	/* make n positive */

	i = 0;
	do 
	{ 	/* generate digits in reverse order */
		s[i++] = n % 10 + '0'; 	/* get next digit */
	} while ((n /= 10) > 0); 	/* delete it */

	if (sign < 0)
		s[i++] = '-';

	s[i] = '\0';
	reverse(s);
}

/* strlen: return length of s */

int 
strlen(char * s)
{
	int i = 0;
	
	while (s[i] != '\0')
		i++;
	
	return i;
}

/* reverse: reverse string s in place */

void 
reverse(char * s)
{
	int c, i, j;

	for (i = 0, j = strlen(s)-1; i < j; i++, j--) 
	{
		c = s[i];
		s[i] = s[j];
		s[j] = c;
	}
}

/* atoi: convert s to integer */

int 
atoi(char * s)
{
	int i, n, sign;

	for (i = 0; isspace(s[i]); i++) 	/* skip white space */
		;
	sign = (s[i] == '-') ? -1 : 1;
	if (s[i] == '+' || s[i] == '-') 	/* skip sign */
		i++;
	for (n = 0; isdigit(s[i]); i++)
		n = 10 * n + (s[i] - '0');

	return sign * n;
}

/* strcmp: return <0 if s<t, 0 if s==t, >0 if s>t */

int 
strcmp(char * s, char * t)
{
	for ( ; *s == *t; s++, t++)
		if (*s == '\0')
			return 0;

	return *s - *t;
}

/* strncmp: return <0 if s<t, 0 if s==t, >0 if s>t */

int
strncmp (char *s, char *t, int n)
{
	for (; *s == *t; s++, t++)
		if (*s == 0 || --n < 0 )
			return 0;
	
	return *s - *t;
}

